<template>
  <view class="warehouse-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">出库作业</text>
    </view>

    <!-- 出库信息区域 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">出库信息</text>
      </view>

      <!-- 出库类型标签页 -->
      <view class="in-type-tabs">
        <view
          class="tab-item"
          :class="{ active: formData.outType === '领料出库' }"
          @click="switchOutType('领料出库')"
        >
          <text class="tab-text">领料出库</text>
        </view>
        <view
          class="tab-item"
          :class="{ active: formData.outType === '人工出库' }"
          @click="switchOutType('人工出库')"
        >
          <text class="tab-text">人工出库</text>
        </view>
        <view
          class="tab-item"
          :class="{ active: formData.outType === '调拨出库' }"
          @click="switchOutType('调拨出库')"
        >
          <text class="tab-text">调拨出库</text>
        </view>
      </view>

      <view class="info-form">
        <view class="form-item">
          <text class="form-label required">出库日期</text>
          <picker
            class="form-picker"
            mode="date"
            :value="formData.outDate"
            @change="handleDateChange"
          >
            <view class="picker-content">
              <text>{{ formData.outDate }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="form-label">目标仓库</text>
          <view class="warehouse-display">{{
            currentWarehouse ? currentWarehouse.warehouseName : "请选择"
          }}</view>
        </view>

        <!-- 领料工序（仅领料出库显示） -->
        <view class="form-item" v-if="formData.outType === '领料出库'">
          <text class="form-label">领料工序</text>
          <view class="process-display">{{ currentProcess.processName }}</view>
        </view>

        <!-- 调拨目标仓库（仅调拨出库显示） -->
        <view class="form-item" v-if="formData.outType === '调拨出库'">
          <text class="form-label required">目标仓库</text>
          <picker
            class="form-picker"
            mode="selector"
            :range="targetWarehouseOptions"
            range-key="warehouseName"
            :value="targetWarehouseIndex"
            @change="handleTargetWarehouseChange"
          >
            <view class="picker-content">
              <text>{{
                targetWarehouseIndex >= 0 &&
                targetWarehouseOptions[targetWarehouseIndex]
                  ? targetWarehouseOptions[targetWarehouseIndex].warehouseName
                  : "请选择目标仓库"
              }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 查询/选择区 -->
    <view class="material-section">
      <view class="section-header">
        <text class="section-title">库存查询</text>
      </view>
      <view class="purchase-search-area">
        <view class="scan-input-group">
          <view class="input-row">
            <input
              v-model="searchForm.materialCode"
              class="material-input"
              placeholder="输入物料编码"
              @confirm="searchMaterials"
            />
            <button class="scan-btn" @click="scanMaterialCode">扫码</button>
          </view>
          <view class="input-row">
            <input
              v-model="searchForm.materialName"
              class="material-input"
              placeholder="输入物料名称"
              @confirm="searchMaterials"
            />
            <button class="search-btn" @click="searchMaterials">搜索</button>
          </view>
        </view>
      </view>
      <view class="tab-header">
        <button
          class="tab-btn"
          :class="{ active: activeTab === 'current' }"
          @click="activeTab = 'current'"
        >
          当前数据 ({{ stockTable.length }})
        </button>
        <button
          class="tab-btn"
          :class="{ active: activeTab === 'selected' }"
          @click="activeTab = 'selected'"
        >
          待出库数据 ({{ outTable.length }})
        </button>
      </view>
      <!-- 库存查询结果表格 -->
      <view
        class="material-table-section"
        v-if="stockTable.length > 0 || outTable.length > 0"
      >
        <!-- 当前数据Tab -->
        <view v-if="activeTab === 'current'" class="tab-content">
          <view class="table-header">
            <text class="header-cell">入库日期</text>
            <text class="header-cell">物料名称</text>
            <text class="header-cell">库存重量(KG)</text>
            <text class="header-cell">库存数量(件)</text>
            <text class="header-cell">出库重量(KG)</text>
            <text class="header-cell">出库数量(件)</text>
            <text class="header-cell">操作</text>
          </view>

          <view v-for="item in stockTable" :key="item.id" class="table-row">
            <text class="table-cell">{{
              dateHelperApi.formatDate(item.createTime)
            }}</text>
            <text class="table-cell">{{ item.materialName }}</text>
            <text class="table-cell">
              {{ item.prodCount }}
            </text>
            <text class="table-cell">
              {{ item.transCount }}
            </text>
            <input
              v-model.number="item.outProdCount"
              type="digit"
              class="table-input"
              :class="{ 'error-input': item.showError && !item.outProdCount }"
              placeholder="重量"
              @blur="validateNumber($event, item, 'outProdCount')"
            />
            <input
              v-model.number="item.outTransCount"
              type="number"
              class="table-input"
              :class="{
                'error-input': item.showError && !item.outTransCount,
              }"
              placeholder="数量"
              @blur="validateNumber($event, item, 'outTransCount')"
            />
            <button class="add-btn" @tap="addToOutList(item)">称重/确认</button>
          </view>
        </view>

        <!-- 待出库数据Tab -->
        <view v-if="activeTab === 'selected'" class="tab-content">
          <view v-if="outTable.length === 0" class="empty-tab-state">
            <text class="empty-text">暂无待出库物料，请在库存中选择物料</text>
          </view>

          <view v-else>
            <view class="table-header">
              <text class="header-cell">出库日期</text>
              <text class="header-cell">物料名称</text>
              <text class="header-cell">出库重量(KG)</text>
              <text class="header-cell">出库数量(件)</text>
              <text class="header-cell">操作</text>
            </view>
            <view class="table-body">
              <view
                v-for="(item, index) in outTable"
                :key="'selected-' + index"
                class="table-row selected-material"
              >
                <text class="table-cell">{{
                  dateHelperApi.formatDate(item.createTime)
                }}</text>
                <text class="table-cell">{{ item.materialName }}</text>
                <text class="table-cell">
                  <span class="out-value">{{ item.outProdCount }}</span>
                </text>
                <text class="table-cell">
                  <span class="out-value">{{ item.outTransCount }}</span>
                </text>
                <text class="table-cell">
                  <button
                    class="remove-btn-small"
                    @click.stop="removeFromOutList(index)"
                  >
                    移除
                  </button>
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 统计条 -->
    <view class="statistics-section">
      <view class="stat-item">
        <text class="stat-label">总数量:</text>
        <text class="stat-value">{{ totalCount }}件</text>
      </view>
      <view class="stat-item">
        <text class="stat-label">总重量:</text>
        <text class="stat-value">{{ totalWeight }}KG</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="action-bar">
      <button class="btn-reset" @click="showResetConfirm">重置</button>
      <button class="btn-submit" @click="submitOutOrder" :disabled="!canSubmit">
        提交出库
      </button>
    </view>
  </view>
</template>

<script>
import { warehouseApi } from "@/api/warehouse/warehouse.js";
import { stockOutApi } from "@/api/warehouse/stockOut";
import { inventoryApi } from "@/api/warehouse/inventory";
import { ProdStockOutApi } from "@/api/warehouse/prodstockout";
import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";

export default {
  data() {
    return {
      // 当前激活的标签页
      activeTab: "current",

      // 表单数据
      formData: {
        outDate: dateHelperApi.getCurrentDate(),
        outType: "领料出库",
        warehouseCode: "",
        warehouseName: "",
      },

      // 当前仓库信息
      currentWarehouse: {
        warehouseCode: "",
        warehouseName: "请选择仓库",
      },

      // 当前工序信息
      currentProcess: {
        processName: "",
      },

      // 目标仓库选项（调拨出库用）
      targetWarehouseOptions: [],
      targetWarehouseIndex: -1,

      // 搜索表单
      searchForm: {
        materialCode: "",
        materialName: "",
      },

      // 时间筛选器
      timeFilter: "today",

      // 库存表格数据
      stockTable: [],

      // 待出库表格数据
      outTable: [],

      // 选中行
      selectedRows: [],

      // 加载状态
      loading: false,
    };
  },

  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },

    // 是否可以提交
    canSubmit() {
      return this.outTable.length > 0;
    },

    // 总数量
    totalCount() {
      return this.outTable.reduce(
        (sum, item) => sum + (Number(item.outTransCount) || 0),
        0
      );
    },

    // 总重量
    totalWeight() {
      return this.outTable.reduce(
        (sum, item) => sum + (Number(item.outProdCount) || 0),
        0
      );
    },
  },

  onLoad() {
    this.initData();
  },

  onBackPress() {
    if (this.outTable.length > 0) {
      uni.showModal({
        title: "提示",
        content: "有待出库数据，确认不操作出库吗？",
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack();
          }
        },
      });
      return true;
    }
  },

  methods: {
    // 初始化数据
    async initData() {
      try {
        // 获取当前仓库信息
        this.loadCurrentWarehouse();

        // 获取当前工序信息
        this.loadCurrentProcess();

        // 获取目标仓库选项（调拨出库用）
        await this.loadTargetWarehouses();
      } catch (error) {
        console.error("初始化数据失败:", error);
        uni.showToast({
          title: "初始化失败",
          icon: "error",
        });
      }
    },

    // 加载当前仓库信息
    loadCurrentWarehouse() {
      const userConfig = this.$store.state.user.userConfig;
      if (userConfig && userConfig.wmName) {
        this.currentWarehouse = {
          warehouseCode: userConfig.wmCode || "DEFAULT",
          warehouseName: userConfig.wmName,
        };
        this.formData.warehouseCode = this.currentWarehouse.warehouseCode;
        this.formData.warehouseName = this.currentWarehouse.warehouseName;
      }
    },

    // 加载当前工序信息
    loadCurrentProcess() {
      const userConfig = this.$store.state.user.userConfig;
      if (userConfig && userConfig.processName) {
        this.currentProcess = {
          processName: userConfig.processName,
        };
      }
    },

    // 加载目标仓库选项
    async loadTargetWarehouses() {
      try {
        // 获取第1页，每页100条数据，筛选原料仓库
        const params = {
          pageNo: 1,
          pageSize: 100,
          dictType: "wm_name_po",
        };
        const response = await warehouseApi.getWarehouseList(params);
        if (response.code === 0) {
          // 将数据转换为下拉选项格式，根据API返回的字段名称
          this.targetWarehouseOptions = (response.data.list || []).map(
            (item) => ({
              value: item.value,
              text: item.label,
              warehouseName: item.label, // 用于显示
            })
          );
          console.log("目标仓库数据加载成功:", this.targetWarehouseOptions);
        }
      } catch (error) {
        console.error("加载目标仓库失败:", error);
      }
    },

    // 切换出库类型
    switchOutType(type) {
      this.formData.outType = type;
      this.targetWarehouseIndex = -1; // 重置目标仓库选择
      this.resetSearch();
      this.selectedRows = [];
    },

    // 选择行
    selectRow(index) {
      const rowIndex = this.selectedRows.indexOf(index);
      if (rowIndex > -1) {
        this.selectedRows.splice(rowIndex, 1);
      } else {
        this.selectedRows.push(index);
      }
    },

    // 处理日期变更
    handleDateChange(e) {
      this.formData.outDate = e.detail.value;
    },

    // 处理目标仓库变更
    handleTargetWarehouseChange(e) {
      this.targetWarehouseIndex = e.detail.value;
      // 获取选中的仓库信息并更新表单数据
      if (
        this.targetWarehouseIndex >= 0 &&
        this.targetWarehouseOptions[this.targetWarehouseIndex]
      ) {
        const selectedWarehouse =
          this.targetWarehouseOptions[this.targetWarehouseIndex];
        this.formData.warehouseCode = selectedWarehouse.value;
        console.log(
          "选中目标仓库:",
          selectedWarehouse.text,
          "仓库编码:",
          selectedWarehouse.value
        );
      }
    },

    // 扫码物料编码
    scanMaterialCode() {
      uni.scanCode({
        success: (res) => {
          this.searchForm.materialCode = res.result;
          this.searchStock();
        },
        fail: (error) => {
          console.error("扫码失败:", error);
          uni.showToast({
            title: "扫码失败",
            icon: "error",
          });
        },
      });
    },

    // 查询库存
    async searchMaterials() {
      if (this.loading) return;

      try {
        console.log("searchForm", this.searchForm);
        console.log("currentWarehouse", this.currentWarehouse);
        this.loading = true;

        const params = {
          pageNum: 1,
          pageSize: 50,
          warehouseName: this.currentWarehouse.warehouseName,
          materialCode: this.searchForm.materialCode,
          materialName: this.searchForm.materialName,
        };

        const response = await inventoryApi.getStockReal(params);

        if (response.code === 0) {
          this.stockTable = (response.data.list || []).map((item) => ({
            ...item,
            outProdCount: item.prod_count || 0,
            outTransCount: item.trans_count || 0,
          }));

          // 搜索成功后默认切换到“当前数据”页签
          this.activeTab = "current";

          if (this.stockTable.length === 0) {
            uni.showToast({
              title: "未查询到库存数据",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: response.msg || "查询失败",
            icon: "error",
          });
        }
      } catch (error) {
        console.error("查询库存失败:", error);
        uni.showToast({
          title: "查询失败",
          icon: "error",
        });
      } finally {
        this.loading = false;
      }
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        materialCode: "",
        materialName: "",
      };
      this.stockTable = [];
      this.selectedRows = [];
    },

    // 数字验证
    validateNumber(item, field) {
      const value = Number(item[field]);
      if (isNaN(value) || value <= 0) {
        uni.showToast({
          title: "请输入有效的数字",
          icon: "none",
        });
        item[field] = 0;
      } else if (value > 999999) {
        uni.showToast({
          title: "数字不能超过999999",
          icon: "none",
        });
        item[field] = 999999;
      }
    },

    // 添加到出库列表
    addToOutList(item) {
      // 检查是否已经添加
      const exists = this.outTable.find((outItem) => outItem.id === item.id);
      if (exists) {
        uni.showToast({
          title: "该物料已在出库列表中",
          icon: "none",
        });
        return;
      }

      // 验证数量（取新字段）
      const prodCount = Number(item.outProdCount) || 0;
      const transCount = Number(item.outTransCount) || 0;

      // 允许单项为 0，但不能同时为 0
      if (prodCount === 0 && transCount === 0) {
        uni.showToast({
          title: "出库重量和数量不能同时为 0",
          icon: "none",
        });
        return;
      }
      // 仍禁止负数
      if (prodCount < 0 || transCount < 0) {
        uni.showToast({
          title: "出库数量不能为负数",
          icon: "none",
        });
        return;
      }

      // 添加到出库列表（带新字段）
      this.outTable.push({
        ...item,
        outProdCount: Number(prodCount) || 0,
        outTransCount: Number(transCount) || 0,
      });

      // 清空选中状态
      this.selectedRows = [];

      uni.showToast({
        title: "已添加到出库列表",
        icon: "success",
      });
    },

    // 从出库列表移除
    removeFromOutList(index) {
      this.outTable.splice(index, 1);
    },

    // 显示重置确认
    showResetConfirm() {
      if (this.outTable.length === 0) {
        this.resetForm();
        return;
      }

      uni.showModal({
        title: "确认重置",
        content: "确定要清空所有数据吗？",
        success: (res) => {
          if (res.confirm) {
            this.resetForm();
          }
        },
      });
    },

    // 重置表单
    resetForm() {
      this.formData = {
        outDate: dateHelperApi.getCurrentDate(),
        outType: "领料出库",
        warehouseCode: this.currentWarehouse.warehouseCode,
        warehouseName: this.currentWarehouse.warehouseName,
      };
      this.searchForm = {
        materialCode: "",
        materialName: "",
      };
      this.timeFilter = "today"; // 重置时间筛选状态
      this.stockTable = [];
      this.outTable = [];
      this.selectedRows = [];
      this.targetWarehouseIndex = -1;
    },

    // 提交出库单
    async submitOutOrder() {
      if (!this.canSubmit) {
        uni.showToast({
          title: "请先添加出库物料",
          icon: "none",
        });
        return;
      }

      // 验证必填项
      if (!this.formData.outDate) {
        uni.showToast({
          title: "请选择出库日期",
          icon: "none",
        });
        return;
      }

      if (
        this.formData.outType === "调拨出库" &&
        this.targetWarehouseIndex === -1
      ) {
        uni.showToast({
          title: "请选择目标仓库",
          icon: "none",
        });
        return;
      }

      try {
        const submitData = this.buildSubmitData();

        // 验证数据构建是否成功
        if (!submitData) {
          return;
        }

        // 显示确认对话框
        const confirmed = await this.showSubmitConfirm(submitData);
        if (!confirmed) return;

        this.loading = true;
        
        // 根据出库类型调用不同的API
        let response;
        if (this.formData.outType === '领料出库') {
          // 领料出库使用生产出库API
          response = await ProdStockOutApi.createProdStockOutPDA(submitData);
        } else {
          // 人工出库和调拨出库使用通用出库API
          response = await stockOutApi.submitOutbound(submitData);
        }

        if (response.code === 0) {
          await this.handleSubmitSuccess(response);
        } else {
          uni.showToast({
            title: response.msg || "提交失败",
            icon: "error",
          });
        }
      } catch (error) {
        console.error("提交出库单失败:", error);
        uni.showToast({
          title: "提交失败",
          icon: "error",
        });
      } finally {
        this.loading = false;
      }
    },

    // 构建提交数据
    buildSubmitData() {
      const userConfig = this.$store.state.user.userConfig;
      const targetWarehouse =
        this.targetWarehouseOptions[this.targetWarehouseIndex];

      // 验证所有物料的重量和数量
      for (let item of this.outTable) {
        if (!item.outProdCount || !item.outTransCount) {
          uni.showToast({
            title: "请填写完整的物料信息",
            icon: "none",
          });
          return null;
        }

        // 验证数字有效性
        if (
          isNaN(Number(item.outProdCount)) ||
          isNaN(Number(item.outTransCount)) ||
          Number(item.outProdCount) < 0 ||
          Number(item.outTransCount) < 0
        ) {
          uni.showToast({
            title: "物料信息格式错误",
            icon: "none",
          });
          return null;
        }
      }

      // 根据出库类型构建不同格式的数据
      if (this.formData.outType === '领料出库') {
        // 领料出库使用生产出库API格式
        return {
          outType: this.formData.outType,
          warehouseCode: this.currentWarehouse.warehouseCode,
          warehouseName: this.currentWarehouse.warehouseName,
          outDate: this.formData.outDate,
          busMemo: "",
          details: this.outTable.map((item) => ({
            materialCode: item.materialCode || "",
            materialName: item.materialName,
            prodCount: Number(item.outProdCount) || 0,
            countUnit: "KG",
            transCount: Number(item.outTransCount) || 0,
            tranUnit: "件",
            spec: item.spec || "",
            picNo: item.picNo || "",
            prodCompany: item.prodCompany || "",
            batchNoSerial: item.batchNoSerial || "",
            steelGradeName: item.steelGradeName || "",
            prodSpec: item.prodSpec || "",
            workShift: userConfig?.workShift || "",
            workType: userConfig?.workClass || "",
            wpEquipCode: "",
          })),
        };
      } else {
        // 人工出库和调拨出库使用通用出库API格式
        return {
          id: null,
          mainNo: "",
          outType: this.formData.outType,
          warehouseCode: this.currentWarehouse.warehouseCode,
          warehouseName: this.currentWarehouse.warehouseName,
          ywDate: this.formData.outDate,
          busMemo: "",
          targetWarehouseCode: targetWarehouse?.value || "",
          targetWarehouseName: targetWarehouse?.text || "",
          details: this.outTable.map((item) => ({
            materialCode: item.materialCode || "",
            materialName: item.materialName,
            prodCount: Number(item.outProdCount) || 0,
            countUnit: "KG",
            transCount: Number(item.outTransCount) || 0,
            tranUnit: "件",
            spec: item.spec || "",
            picNo: item.picNo || "",
            prodCompany: item.prodCompany || "",
            batchNoSerial: item.batchNoSerial || "",
            steelGradeName: item.steelGradeName || "",
            prodSpec: item.prodSpec || "",
            workShift: userConfig?.workShift || "",
            workType: userConfig?.workClass || "",
            wpEquipCode: "",
          })),
        };
      }
    },

    // 显示提交确认
    showSubmitConfirm(submitData) {
      return new Promise((resolve) => {
        const materialCount = submitData.details.length;
        const totalWeight = submitData.details.reduce(
          (sum, item) => sum + item.outProdCount,
          0
        );
        const totalQuantity = submitData.details.reduce(
          (sum, item) => sum + item.outTransCount,
          0
        );

        uni.showModal({
          title: "确认提交",
          content: `共${materialCount}条物料，总重量：${totalWeight}KG，总数量：${totalQuantity}件，是否确认提交？`,
          confirmText: "确认",
          cancelText: "取消",
          success: (res) => {
            resolve(res.confirm);
          },
        });
      });
    },

    // 处理提交成功
    async handleSubmitSuccess(response) {
      uni.showToast({
        title: "出库单创建成功",
        icon: "success",
        duration: 2000,
      });

      console.log("出库单创建成功:", response.data);

      // 重置表单
      this.resetForm();

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 2000);
    },
  },
};
</script>
<style scoped lang="scss">
@import "~@/pages/smart/scss/create.scss";
</style>
